<script setup lang="ts">
import type {ProductItem, ProductSku, ProductSkuRequestData} from "./apis/type"
import {showImagePreview, showToast} from "vant"
import {getProductById, getProductSkuById, getShipFee, getWeight} from "./apis"
import html2canvas from 'html2canvas'

const route = useRoute()

const product = ref<ProductItem>({
  id: 0,
  brandId: 0,
  categoryId: 0,
  code: "",
  dyed: "",
  finishing: "",
  introduction: "",
  laser: "",
  material: "",
  picUrl: "",
  polish: "",
  status: 0,
  unit: ""
})

const colors = ref<string[]>([])
const sizes = ref<string[]>([])
const weights = ref<Map<string, number>>(new Map())
const totalPrice = ref(0)
const totalPurchasePrice = ref(0)

interface ProductInfo {
  property: string
  salePriceUs: number
  purchasePriceUs: number
  weight: number
  id: string
  checked: boolean
  count: number
  totalPrice: number
  totalPurchasePrice: number
  stock: number
}

const productInfos = ref<Map<string, ProductInfo>>(new Map())

const skus = ref<ProductSku[]>([
  {
    id: "",
    propertyInfo: "",
    propertyList: [],
    property: "",
    salePriceUs: 0,
    purchasePriceUs: 0,
    stock: 0
  }
])

export interface ShipColums {
  text: string
  value: number
}

const chooseShipFeeText = ref("No")
const chooseShipFee = ref(0)
const showPicker = ref(false)
const columns = ref<ShipColums[]>([])
const totalWeight = ref(0)
const sheepFee = ref(0)

function onConfirm({selectedOptions}: { selectedOptions: ShipColums[] }) {
  showPicker.value = false
  chooseShipFeeText.value = selectedOptions[0].text
  chooseShipFee.value = selectedOptions[0].value
}

function showImage(url: string) {
  showImagePreview({
    images: [
      url
    ],
    closeable: true
  })
}

function clickSku(property: string) {
  if (!productInfos.value.get(property)) {
    return
  }
  const info = productInfos.value.get(property)
  if (info !== undefined) {
    info.checked = !info.checked
    productInfos.value.set(property, info)
  }
}

function cal() {
  totalPrice.value = 0
  totalPurchasePrice.value = 0
  totalWeight.value = 0
  sheepFee.value = 0
  for (const item of productInfos.value.values()) {
    if (item.checked) {
      item.totalPrice = item.salePriceUs * item.count
      item.totalPurchasePrice = item.purchasePriceUs * item.count
      totalPrice.value += item.totalPrice
      totalPurchasePrice.value += item.totalPurchasePrice
      totalWeight.value += item.count * item.weight
    }
  }
  sheepFee.value = totalWeight.value * chooseShipFee.value / 1000
  // totalPurchasePrice.value += sheepFee.value
  // totalPrice.value += sheepFee.value
}

onMounted(() => {
  const id = route.params.id as string
  getProductById({id}).then((data) => {
    product.value = data.data
  })

  const params: ProductSkuRequestData = {
    productId: id
  }

  getWeight(params).then((res) => {
    getProductSkuById(params).then((data) => {
      skus.value = data.data
      skus.value.forEach((item) => {
        item.propertyList = JSON.parse(item.property)
        let key: string = ""
        let weight: number = 0
        item.propertyList.forEach((property) => {
          if (property.code === 3) {
            if(!sizes.value.includes(property.value)) {
              sizes.value.push(property.value)
            }
            key += property.value
            res.data.forEach(weightItem => {
              if (weightItem.size === property.value) {
                weight = weightItem.weight
              }
            })
            console.log(weight)
            weights.value.set(property.value, weight)
          }
          if (property.code === 4) {
            if(!colors.value.includes(property.value)) {
              colors.value.push(property.value)
            }
            key = key + property.value
          }
        })
        const info: ProductInfo = {
          property: item.propertyInfo,
          salePriceUs: item.salePriceUs,
          purchasePriceUs: item.purchasePriceUs,
          weight: weight,
          id: item.id,
          checked: false,
          count: 0,
          totalPrice: 0,
          totalPurchasePrice: 0,
          stock: item.stock,
        }
        productInfos.value.set(key, info)
      })
      console.log(weights.value)

      // size 排序
      sizes.value.sort()
    })
  })

  getShipFee().then((data) => {
    columns.value.push({text: "No", value: 0})
    data.data.forEach((item) => {
      columns.value.push({text: item.location, value: item.usPrice})
    })
  })

  totalWeight.value = 0

})

function formatCurrency(value: number | undefined) {
  if (value) {
    return new Intl.NumberFormat("de-DE").format(value)
  }
}

// 状态管理
const isLoading = ref(false)
const screenshotUrl = ref("")
const needShowToast = ref(false)
const toastMessage = ref("")

// 处理截图
async function saveImage() {
  isLoading.value = true
  try {
    // 等待DOM更新
    await nextTick()

    // 获取目标元素
    const targetElement = document.querySelector(".screenshot-target")
    if (!targetElement) {
      throw new Error("The target element for screenshot was not found")
    }

    const option = {
      useCORS: true, // 允许跨域图片
      logging: false, // 禁用日志
      scale: window.devicePixelRatio, // 保持高清
      backgroundColor: null // 背景透明
    }
    // 使用html2canvas生成截图
    const canvas = await html2canvas(<HTMLElement>targetElement, option)

    // 将canvas转换为图片URL
    screenshotUrl.value = canvas.toDataURL("image/png")
    console.log(screenshotUrl.value)

    // 显示预览
    // showPreview.value = true
    showImagePreview([screenshotUrl.value]);

    // showToast({
    //   message: "Screenshot successful",
    //   type: "success"
    // })
  } catch (error) {
    console.error("Screenshot failed:", error)
    // const option = {
    //   message: "Screenshot failed",
    //   type: "fail"
    // }
    // showToast(option)
  } finally {
    isLoading.value = false
  }
}
</script>

<template>
  <div un-py-16px class="screenshot-target">
    <van-cell-group inset>
      <van-cell title="Ref.No" :value="product.code"/>
      <van-cell title="Picture" v-if="product.picUrl">
        <template #value>
          <van-image :src="product.picUrl" @click="showImage(product.picUrl)" width="10rem"/>
        </template>
      </van-cell>

    </van-cell-group>

    <div style="height: 10px"/>
    <div style="margin: var(--van-cell-group-inset-padding);background: white;">
      <div style="display: flex">
        <div class="btn_tab">
          A
        </div>
        <div class="btn_tab" v-for="size in sizes" :key="size">
          {{ size }}
        </div>
      </div>
    </div>
    <div style="margin: var(--van-cell-group-inset-padding);background: white;">
      <div style="display: flex">
        <div class="btn_tab">
          Weight
        </div>
        <div class="btn_tab" v-for="size in sizes" :key="size">
          {{ weights.get(size) }}g
        </div>
      </div>
    </div>
    <div v-for="color in colors" :key="color" style="margin: var(--van-cell-group-inset-padding);background: white;">
      <div style="display: flex">
        <div class="btn_tab">
          {{ color }}
        </div>
        <div @click="clickSku(`${color}${size}`)"
             :class="productInfos.get(`${color}${size}`)?.checked ? 'btn_tab_active' : 'btn_tab'" v-for="size in sizes"
             :key="size">
          <template v-if="productInfos.get(`${color}${size}`)">
            ${{ formatCurrency(productInfos.get(`${color}${size}`)?.salePriceUs) }} / ${{ formatCurrency(productInfos.get(`${color}${size}`)?.purchasePriceUs) }}
            <br/>
            Stock: {{productInfos.get(`${color}${size}`)?.stock}}
          </template>
        </div>
      </div>
    </div>
    <div style="height: 10px"/>

    <van-cell-group inset>
      <template v-for="item in productInfos.values()" :key="item.id">
        <van-field v-if="item.checked" type="digit" :label="item.property" v-model="item.count" @change="cal" placeholder="Input Count"/>
      </template>
      <van-cell v-if="totalWeight > 0" title="Weight" :value="formatCurrency(totalWeight)"/>
      <van-field v-if="totalWeight > 0" type="number" label="Ship Price/kg" v-model="chooseShipFee" @change="cal" placeholder="Input Price"/>
      <van-cell v-if="totalWeight > 0" title="ShipFee" :value="formatCurrency(sheepFee)"/>
      <van-cell title="ProductPrice" :value="formatCurrency(totalPrice)"/>
      <van-cell title="TotalPrice" :value="formatCurrency(totalPrice + sheepFee)"/>
      <van-cell title="PurchasePrice" :value="formatCurrency(totalPurchasePrice)"/>
      <van-cell data-html2canvas-ignore="true">
        <template #title>
          <van-button @click="saveImage" text="SaveAsImage" type="default" size="small"/>
        </template>
        <template #value>
          <van-button @click="cal" text="Cal" type="primary" size="small"/>
        </template>
      </van-cell>
      <div style="height: 20px;"></div>
    </van-cell-group>

    <van-popup v-model:show="showPicker" round position="bottom">
      <van-picker
        :columns="columns"
        @cancel="showPicker = false"
        @confirm="onConfirm"
      />
    </van-popup>

    <van-toast
      v-model="needShowToast"
      :message="toastMessage"
      type="success"
      :duration="2000"
    />
  </div>
</template>

<style scoped>
.btn_tab {
  flex: 1;
  border: 1px solid #f7f8fa;
  padding: 10px;
}

.btn_tab_active {
  flex: 1;
  border: 1px solid #f7f8fa;
  padding: 10px;
  background: #1989fa;
  color: white;
}

.screenshot-target {
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.popup-actions {
  padding: 16px;
  border-top: 1px solid #eee;
}

.popup-actions >>> .van-button {
  width: 100%;
}
</style>
